import requests
import json
from datetime import datetime

class LicenseAdmin:
    def __init__(self, server_url, admin_key):
        self.server_url = server_url
        self.admin_key = admin_key
    
    def create_license(self, user_name, user_email, days=365, max_activations=1):
        """创建新的license"""
        url = f"{self.server_url}/api/license/create"
        data = {
            'admin_key': self.admin_key,
            'user_name': user_name,
            'user_email': user_email,
            'days': days,
            'max_activations': max_activations
        }
        
        try:
            response = requests.post(url, json=data)
            result = response.json()
            
            if result.get('success'):
                print(f"License创建成功!")
                print(f"用户: {user_name} ({user_email})")
                print(f"License Key: {result['license_key']}")
                print(f"过期时间: {result['expire_at']}")
                return result['license_key']
            else:
                print(f"创建失败: {result.get('message')}")
                return None
                
        except Exception as e:
            print(f"请求失败: {e}")
            return None
    
    def list_licenses(self, page=1, per_page=20):
        """获取license列表"""
        url = f"{self.server_url}/api/license/list"
        data = {
            'admin_key': self.admin_key,
            'page': page,
            'per_page': per_page
        }
        
        try:
            response = requests.post(url, json=data)
            result = response.json()
            
            if result.get('success'):
                print(f"\n=== License列表 (第{page}页，共{result['pages']}页) ===")
                print(f"总数: {result['total']}")
                print("-" * 100)
                
                for license_info in result['licenses']:
                    status = "✅ 激活" if license_info['is_active'] else "❌ 禁用"
                    expire_date = datetime.fromisoformat(license_info['expire_at']).strftime('%Y-%m-%d')
                    
                    print(f"ID: {license_info['id']}")
                    print(f"Key: {license_info['license_key']}")
                    print(f"用户: {license_info['user_name']} ({license_info['user_email']})")
                    print(f"状态: {status} | 过期: {expire_date}")
                    print(f"激活: {license_info['current_activations']}/{license_info['max_activations']}")
                    if license_info['machine_id']:
                        print(f"绑定设备: {license_info['machine_id']}")
                    print("-" * 50)
                
                return result['licenses']
            else:
                print(f"获取失败: {result.get('message')}")
                return None
                
        except Exception as e:
            print(f"请求失败: {e}")
            return None
    
    def deactivate_license(self, license_key):
        """禁用license"""
        url = f"{self.server_url}/api/license/deactivate"
        data = {
            'admin_key': self.admin_key,
            'license_key': license_key
        }
        
        try:
            response = requests.post(url, json=data)
            result = response.json()
            
            if result.get('success'):
                print(f"License {license_key} 已禁用")
                return True
            else:
                print(f"禁用失败: {result.get('message')}")
                return False
                
        except Exception as e:
            print(f"请求失败: {e}")
            return False

def main():
    # 配置
    SERVER_URL = "http://localhost:5000"  # 您的服务器地址
    ADMIN_KEY = "your-admin-secret-key"   # 管理员密钥
    
    admin = LicenseAdmin(SERVER_URL, ADMIN_KEY)
    
    while True:
        print("\n=== License管理工具 ===")
        print("1. 创建License")
        print("2. 查看License列表")
        print("3. 禁用License")
        print("0. 退出")
        
        choice = input("请选择操作: ").strip()
        
        if choice == '1':
            user_name = input("用户姓名: ").strip()
            user_email = input("用户邮箱: ").strip()
            days = input("有效期(天，默认365): ").strip()
            days = int(days) if days else 365
            
            admin.create_license(user_name, user_email, days)
            
        elif choice == '2':
            page = input("页码(默认1): ").strip()
            page = int(page) if page else 1
            admin.list_licenses(page)
            
        elif choice == '3':
            license_key = input("要禁用的License Key: ").strip()
            admin.deactivate_license(license_key)
            
        elif choice == '0':
            break
        else:
            print("无效选择")

if __name__ == '__main__':
    main()